'''
@Project ：pythonApiTest 
@File    ：MySQLReporter.py
@IDE     ：PyCharm 
@Author  ：胡文
@Date    ：2025/2/28 上午9:38 
'''
import pymysql
from datetime import datetime


class MySQLReporter:
    def __init__(self):
        self.conn = pymysql.connect(
            host='localhost',
            user='root',
            password='123456',
            database='test_report'
        )

    def save_result(self, case, response, assert_result):
        with self.conn.cursor() as cursor:
            sql = """INSERT INTO test_results 
                     (case_id, request_data, response_data, assertions, is_success) 
                     VALUES (%s, %s, %s, %s, %s)"""
            cursor.execute(sql, (
                case['case_id'],
                json.dumps(case['params']),
                response.text if response else '',
                json.dumps(assert_result),
                all(assert_result.values())
            ))
        self.conn.commit()